/**  
 * @Title: SecretUtil.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2024-01-25 10:46:38 
 */  
package com.fsxgt.datagrid.datax.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.alibaba.fastjson2.JSONWriter;
import com.fsxgt.datagrid.ds.utils.AESUtil;

/**  
 * @ClassName: SecretUtil
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2024-01-25 10:46:38 
*/
public class DataxSecretUtil {

	
	public static String dataxEnCrypt(String text) {
		
		JSONObject object = ((JSONObject)JSON.parse(text));
		
		JSONArray array=(JSONArray)(JSONPath.eval(object, "$..parameter[?(@.username)]"));
		
		for(Object o:array) {
			String password=((JSONObject)o).getString("password");
			String username=((JSONObject)o).getString("username");

			if(password!=null&&!AESUtil.isCrypt(password)) {
				((JSONObject)o).put("password", AESUtil.encrypt(password));
			}
			if(username!=null&&!AESUtil.isCrypt(username)) {
				((JSONObject)o).put("username", AESUtil.encrypt(username));
			}
			
		}
		return JSON.toJSONString(object, JSONWriter.Feature.PrettyFormat);
	}
	
	public static String dataxDeCrypt(String text) {
		
		JSONObject object = ((JSONObject)JSON.parse(text));
		   
		JSONArray array=(JSONArray)(JSONPath.eval(object, "$..parameter[?(@.username)]"));
		
		for(Object o:array) {
			String password=((JSONObject)o).getString("password");
			String username=((JSONObject)o).getString("username");
			
			String pd=AESUtil.decrypt(password);
			String ue=AESUtil.decrypt(username);

			if(password!=null) {
				((JSONObject)o).put("password", pd!=null?pd:password);
			}
			if(username!=null) {
				((JSONObject)o).put("username", ue!=null?ue:username);
			}
			
		}
		return JSON.toJSONString(object, JSONWriter.Feature.PrettyFormat);
	}
}
